<template>
  <el-card>
    <span>产品名称</span>
    <el-tabs v-model="activeName">
      <el-tab-pane label="产品信息" name="basic">
        <basic-info-form ref="basicInfo" :info="info" />
      </el-tab-pane>
      <el-tab-pane label="物模型" name="cloum">
        <el-tabs v-model="activeClumnName">
          <el-tab-pane label="属性定义" name="shuxing">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handlePropertieAdd"
                  v-hasPermi="['jetLinks:devProduct:add']"
                >新增</el-button>
              </el-col>
            </el-row>

            <el-table ref="propertieTable" v-loading="propertieLoading" :data="properties" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="属性标识" align="center" prop="id" />
              <el-table-column label="属性名称" align="center" prop="name" />
              <el-table-column label="数据类型" align="center" prop="valueType.type" />
              <el-table-column label="属性值来源" align="center" prop="expands.source" />
              <el-table-column label="是否只读" align="center" prop="expands.readOnly" />
              <el-table-column label="说明" align="center" prop="description" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- <pagination
              v-show="propertieTotal>0"
              :total="propertieTotal"
              :page.sync="propertieQueryParams.pageNum"
              :limit.sync="propertieQueryParams.pageSize"
              @pagination="getList"
            /> -->

          </el-tab-pane>
          <el-tab-pane label="功能定义" name="gongneng">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleFunctionAdd"
                  v-hasPermi="['jetLinks:devProduct:add']"
                >新增</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="functiontLoading" :data="functions" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="功能标识" align="center" prop="id" />
              <el-table-column label="名称" align="center" prop="name" />
              <el-table-column label="是否异步" align="center" prop="async" />
              <el-table-column label="描述" align="center" prop="description" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- <pagination
              v-show="functionTotal>0"
              :total="functionTotal"
              :page.sync="functionQueryParams.pageNum"
              :limit.sync="functionQueryParams.pageSize"
              @pagination="getList"
            /> -->
          </el-tab-pane>
          <el-tab-pane label="事件定义" name="shijian">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleEventAdd"
                  v-hasPermi="['jetLinks:devProduct:add']"
                >新增</el-button>
              </el-col>
            </el-row>
            <el-table v-loading="eventLoading" :data="events" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="事件标识" align="center" prop="id" />
              <el-table-column label="名称" align="center" prop="name" />
              <el-table-column label="事件级别" align="center" prop="expands.level" />
              <el-table-column label="描述" align="center" prop="description" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- <pagination
              v-show="eventTotal>0"
              :total="eventTotal"
              :page.sync="eventQueryParams.pageNum"
              :limit.sync="eventQueryParams.pageSize"
              @pagination="getList"
            /> -->
          </el-tab-pane>
          <el-tab-pane label="标签定义" name="biaoqian">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleTagAdd"
                  v-hasPermi="['jetLinks:devProduct:add']"
                >新增</el-button>
              </el-col>
            </el-row>
            <el-table v-loading="tagLoading" :data="tags" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="属性标识" align="center" prop="id" />
              <el-table-column label="属性名称" align="center" prop="name" />
              <el-table-column label="数据类型" align="center" prop="valueType.type" />
              <el-table-column label="是否只读" align="center" prop="expands.readOnly" />
              <el-table-column label="说明" align="center" prop="description" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['jetLinks:devProduct:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- <pagination
              v-show="tagTotal>0"
              :total="tagTotal"
              :page.sync="tagQueryParams.pageNum"
              :limit.sync="tagQueryParams.pageSize"
              @pagination="getList"
            /> -->
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
      <el-tab-pane label="告警设置" name="genInfo">
        <gen-info-form ref="genInfo" :info="info" :tables="tables" :menus="menus"/>
      </el-tab-pane>
    </el-tabs>
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :title="propertie.title" :visible.sync="propertie.open" width="500px" append-to-body>
      <el-form ref="propertieForm" :model="propertieForm" :rules="propertieRules" label-width="80px">
        <el-form-item label="属性标识" prop="id">
          <el-input v-model="propertieForm.id" placeholder="请输入属性标识" />
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="propertieForm.name" placeholder="请输入属性名称" />
        </el-form-item>

        <el-form-item label="数据类型" prop="source">
          <el-select v-model="propertieForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataTypes"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据来源" prop="source">
          <el-select v-model="propertieForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataSources"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否只读" prop="deviceType">
          <el-radio-group v-model="propertieForm.expands.readOnly" size="medium">
            <el-radio v-for="(item, index) in deviceTypeOptions" :key="index" :label="item.dictValue"
              :disabled="item.disabled">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="描述" prop="description">
          <el-input v-model="propertieForm.description" type="textarea" placeholder="请输入描述"
            :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelPropertie">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="functionA.title" :visible.sync="functionA.open" width="500px" append-to-body>
      <el-form ref="functionForm" :model="functionForm" :rules="functionRules" label-width="80px">
        <el-form-item label="属性标识" prop="id">
          <el-input v-model="functionForm.id" placeholder="请输入属性标识" />
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="functionForm.name" placeholder="请输入属性名称" />
        </el-form-item>

        <el-form-item label="数据类型" prop="source">
          <el-select v-model="functionForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataTypes"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据来源" prop="source">
          <el-select v-model="functionForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataSources"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否只读" prop="deviceType">
          <el-radio-group v-model="functionForm.expands.readOnly" size="medium">
            <el-radio v-for="(item, index) in deviceTypeOptions" :key="index" :label="item.dictValue"
              :disabled="item.disabled">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="描述" prop="description">
          <el-input v-model="functionForm.description" type="textarea" placeholder="请输入描述"
            :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelFunction">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="eventA.title" :visible.sync="eventA.open" width="500px" append-to-body>
      <el-form ref="eventForm" :model="eventForm" :rules="eventRules" label-width="80px">
        <el-form-item label="属性标识" prop="id">
          <el-input v-model="eventForm.id" placeholder="请输入属性标识" />
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="eventForm.name" placeholder="请输入属性名称" />
        </el-form-item>

        <el-form-item label="数据类型" prop="source">
          <el-select v-model="eventForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataTypes"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据来源" prop="source">
          <el-select v-model="eventForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataSources"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否只读" prop="deviceType">
          <el-radio-group v-model="eventForm.expands.readOnly" size="medium">
            <el-radio v-for="(item, index) in deviceTypeOptions" :key="index" :label="item.dictValue"
              :disabled="item.disabled">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="描述" prop="description">
          <el-input v-model="eventForm.description" type="textarea" placeholder="请输入描述"
            :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelEvent">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="tagA.title" :visible.sync="tagA.open" width="500px" append-to-body>
      <el-form ref="tagForm" :model="tagForm" :rules="tagRules" label-width="80px">
        <el-form-item label="属性标识" prop="id">
          <el-input v-model="tagForm.id" placeholder="请输入属性标识" />
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入属性名称" />
        </el-form-item>

        <el-form-item label="数据类型" prop="source">
          <el-select v-model="tagForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataTypes"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据来源" prop="source">
          <el-select v-model="tagForm.valueType.type" placeholder="请选择">
            <el-option
              v-for="dict in dataSources"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否只读" prop="deviceType">
          <el-radio-group v-model="tagForm.expands.readOnly" size="medium">
            <el-radio v-for="(item, index) in deviceTypeOptions" :key="index" :label="item.dictValue"
              :disabled="item.disabled">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="描述" prop="description">
          <el-input v-model="tagForm.description" type="textarea" placeholder="请输入描述"
            :autosize="{minRows: 1, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelTag">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>

</template>
<script>
import { getGenTable, updateGenTable } from "@/api/tool/gen";
import { optionselect as getDictOptionselect } from "@/api/system/dict/type";
import { listMenu as getMenuTreeselect } from "@/api/system/menu";
import basicInfoForm from "./basicInfoForm";
import genInfoForm from "./genInfoForm";
import Sortable from 'sortablejs';
import { listDevProduct, getDevProduct, delDevProduct, addDevProduct, updateDevProduct, exportDevProduct } from "@/api/jetLinks/devProduct";

export default {
  name: "GenEdit",
  components: {
    basicInfoForm,
    genInfoForm
  },
  data() {
    return {
      // 选中选项卡的 name
      activeName: "basic",
      activeClumnName: "shuxing",
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 表信息
      tables: [],
      // 表列信息
      cloumns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 表详细信息
      info: {},
      //属性信息
      properties:[],
      propertieLoading :false,
      propertieTotal :0,
      propertieQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name : null,
      },
      propertie : {
        title:"添加属性",
        open : false
      },
      propertieForm : {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      },
      propertieRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
       //功能信息
      functions:[],
      functiontLoading :false,
      functionTotal :0,
      functionQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name : null,
      },

      functionA : {
        title:"添加功能",
        open : false
      },
      functionForm : {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      },
      functionRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      //事件信息
      events:[],
      eventLoading :false,
      eventTotal :0,
      eventQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name : null,
      },
      eventA : {
        title:"添加事件",
        open : false
      },
      eventForm : {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      },
      // 校验
      eventRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      //标签信息
      tags:[],
      tagTotal :0,
      tagLoading :false,
      tagQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name : null,
      },
      tagA : {
        title:"添加事件",
        open : false
      },
      tagForm : {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      },
      // 表单校验
      tagRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      //数据来源
      dataSources:[],
      //数据类型
      dataTypes:[],
    };
  },
  created() {
    const tableId = this.$route.query && this.$route.query.tableId;
    if (tableId) {
      // // 获取表详细信息
      // getGenTable(tableId).then(res => {
      //   this.cloumns = res.data.rows;
      //   this.info = res.data.info;
      //   this.tables = res.data.tables;
      // });

      getDevProduct(tableId).then(response => {
        const metadata =  JSON.parse(response.data.metadata);
        this.info = response.data;
        this.properties = metadata.properties;
        this.propertieTotal = metadata.properties.length;
        this.events = metadata.events;
        this.eventTotal = metadata.events.length;
        this.functions = metadata.functions;
        this.functionTotal = metadata.functions.length;
        this.tags = metadata.tags;
        this.tagTotal = metadata.tags.length;
      });
      /** 查询字典下拉列表 */
      getDictOptionselect().then(response => {
        this.dictOptions = response.data;
      });
      /** 查询菜单下拉列表 */
      getMenuTreeselect().then(response => {
        this.menus = this.handleTree(response.data, "menuId");
      });

      //数据来源
      this.getDicts("data_sources").then(response => {
        this.dataSources = response.data;
      });

      //数据类型
      this.getDicts("data_type").then(response => {
        this.dataTypes = response.data;
      });
    }
  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      const basicForm = this.$refs.basicInfo.$refs.basicInfoForm;
      const genForm = this.$refs.genInfo.$refs.genInfoForm;
      Promise.all([basicForm, genForm].map(this.getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
          const genTable = Object.assign({}, basicForm.model, genForm.model);
          genTable.columns = this.cloumns;
          genTable.params = {
            treeCode: genTable.treeCode,
            treeName: genTable.treeName,
            treeParentCode: genTable.treeParentCode,
            parentMenuId: genTable.parentMenuId
          };
          updateGenTable(genTable).then(res => {
            this.msgSuccess(res.msg);
            if (res.code === 200) {
              this.close();
            }
          });
        } else {
          this.msgError("表单校验未通过，请重新检查提交内容");
        }
      });
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    /** 关闭按钮 */
    close() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/equipment/devProduct", query: { t: Date.now()}})
    },
    //属性
    /** 新增按钮操作 */
    handlePropertieAdd() {
      this.propertieReset();
      this.propertie.open = true;
      this.propertie.title = "添加属性";
    },
    cancelPropertie(){
      this.propertieReset();
      this.propertie.open = false;
    },
    propertieReset(){
      this.propertieForm = {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      }
    },
    //功能
    /** 新增按钮操作 */
    handleFunctionAdd() {
      this.functionReset();
      this.functionA.open = true;
      this.functionA.title = "添加功能";
    },
    cancelFunction(){
      this.functionReset();
      this.functionA.open = false;
    },
    functionReset(){
      this.functionForm = {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      }
    },
    //事件
    /** 新增按钮操作 */
    handleEventAdd() {
      this.eventReset();
      this.eventA.open = true;
      this.eventA.title = "添加事件";
    },
    cancelEvent(){
      this.eventReset();
      this.eventA.open = false;
    },
    eventReset(){
      this.eventForm = {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      }
    },
     //标签信息
    handleTagAdd() {
      this.tagReset();
      this.tagA.open = true;
      this.tagA.title = "添加标签";
    },
    cancelTag(){
      this.tagReset();
      this.tagA.open = false;
    },
    tagReset(){
      this.tagForm = {
        "id" : null,
        "name" : null,
        "valueType":{
            "type" : null,
            "unit" : null
        },
        "expands":{
            "readOnly" : null,
            "source" : null
        },
        "description": null
      }
    },
     // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

  },
  mounted() {
    const el = this.$refs.propertieTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
    const sortable = Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: evt => {
        const targetRow = this.cloumns.splice(evt.oldIndex, 1)[0];
        this.cloumns.splice(evt.newIndex, 0, targetRow);
        for (let index in this.cloumns) {
          this.cloumns[index].sort = parseInt(index) + 1;
        }
      }
    });
  }
};
</script>
